<template>
  <common-layout title="采购入库">
    <template #header-buttons>
      <el-button type="primary" @click="handleCreate">创建采购入库单</el-button>
    </template>

    <template #search-form>
      <el-form :inline="true" :model="searchForm" class="mb-4">
        <el-form-item label="入库单号">
          <el-input v-model="searchForm.stockInCode" placeholder="请输入入库单号" />
        </el-form-item>
        <el-form-item label="入库日期">
          <el-date-picker
            v-model="searchForm.stockInDate"
            type="date"
            placeholder="请选择入库日期"
          />
        </el-form-item>
        <el-form-item label="仓库">
          <WarehouseSelect
            v-model="searchForm.warehouseId"
            placeholder="请选择仓库"
            show-all-option
          />
        </el-form-item>
        <el-form-item label="供应商">
          <el-select v-model="searchForm.supplierId" placeholder="请选择供应商">
            <el-option label="全部" value="" />
            <el-option v-for="supplier in suppliers" :key="supplier.id" :label="supplier.supplierName" :value="supplier.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="采购订单号">
          <el-input v-model="searchForm.purchaseOrderCode" placeholder="请输入采购订单号" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="待审核" value="pending" />
            <el-option label="已审核" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已作废" value="canceled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </template>

    <template #data-content>
      <el-table :data="stockInList" style="width: 100%">
        <el-table-column prop="stockInCode" label="入库单号" width="180" />
        <el-table-column prop="stockInDate" label="入库日期" width="120" />
        <el-table-column prop="warehouseName" label="仓库" width="150" />
        <el-table-column prop="supplierName" label="供应商" width="180" />
        <el-table-column prop="purchaseOrderCode" label="采购订单号" width="180" />
        <el-table-column prop="totalQuantity" label="总数量" width="100" />
        <el-table-column prop="totalAmount" label="总金额" width="120" />
        <el-table-column prop="status" label="状态" width="100" :formatter="formatStatus" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="primary" v-if="row.status === 'pending'" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="primary" v-if="row.status === 'pending'" @click="handleApprove(row)">审核</el-button>
            <el-button size="small" type="danger" v-if="row.status === 'pending'" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 查看/编辑/创建对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="70%"
      >
        <el-form :model="stockInForm" ref="stockInFormRef" label-width="120px">
          <el-form-item label="入库单号" :required="true">
            <el-input v-model="stockInForm.stockInCode" :disabled="dialogType !== 'create'" />
          </el-form-item>
          <el-form-item label="入库日期" :required="true">
            <el-date-picker
              v-model="stockInForm.stockInDate"
              type="date"
              placeholder="请选择入库日期"
              :disabled="dialogType === 'view'"
            />
          </el-form-item>
          <el-form-item label="仓库" :required="true">
            <WarehouseSelect
              v-model="stockInForm.warehouseId"
              placeholder="请选择仓库"
              :disabled="dialogType === 'view'"
            />
          </el-form-item>
          <el-form-item label="供应商" :required="true">
            <el-select v-model="stockInForm.supplierId" placeholder="请选择供应商" :disabled="dialogType === 'view'">
              <el-option v-for="supplier in suppliers" :key="supplier.id" :label="supplier.supplierName" :value="supplier.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="采购订单号" :required="true">
            <el-select v-model="stockInForm.purchaseOrderId" placeholder="请选择采购订单" :disabled="dialogType === 'view'">
              <el-option v-for="order in purchaseOrders" :key="order.id" :label="order.orderCode" :value="order.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="stockInForm.remark" type="textarea" :disabled="dialogType === 'view'" />
          </el-form-item>
        </el-form>

        <el-divider />

        <div class="detail-title">物料明细</div>
        <el-table :data="stockInForm.details" border style="width: 100%" v-if="stockInForm.details && stockInForm.details.length > 0">
          <el-table-column prop="lineNum" label="行号" width="80" />
          <el-table-column prop="materialCode" label="物料编码" width="150" />
          <el-table-column prop="materialName" label="物料名称" width="180" />
          <el-table-column prop="specification" label="规格型号" width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="orderQuantity" label="订单数量" width="100" />
          <el-table-column prop="inQuantity" label="入库数量" width="100" :disabled="dialogType === 'view'">
            <template #default="{ row }">
              <el-input v-model="row.inQuantity" type="number" :disabled="dialogType === 'view'" />
            </template>
          </el-table-column>
          <el-table-column prop="unitPrice" label="单价" width="100" />
          <el-table-column prop="amount" label="金额" width="120" />
          <el-table-column prop="batchNumber" label="批次号" width="150" />
          <el-table-column prop="productionDate" label="生产日期" width="120" />
          <el-table-column prop="expiryDate" label="失效日期" width="120" />
        </el-table>

        <div v-else class="no-data">暂无物料明细</div>

        <!-- 审核表单 -->
        <div v-if="dialogType === 'approve'" class="approve-form mt-4">
          <el-form :model="approveForm" ref="approveFormRef" label-width="120px">
            <el-form-item label="审核备注">
              <el-input v-model="approveForm.approvalRemark" type="textarea" />
            </el-form-item>
          </el-form>
        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button v-if="dialogType !== 'view' && dialogType !== 'approve'" type="primary" @click="handleSubmit">确定</el-button>
            <el-button v-if="dialogType === 'approve'" type="primary" @click="handleApproveSubmit">通过</el-button>
            <el-button v-if="dialogType === 'approve'" type="danger" @click="handleRejectSubmit">拒绝</el-button>
          </div>
        </template>
      </el-dialog>
    </template>
  </common-layout>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import WarehouseSelect from '../components/WarehouseSelect.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 搜索表单数据
const searchForm = reactive({
  stockInCode: '',
  stockInDate: '',
  warehouseId: '',
  supplierId: '',
  purchaseOrderCode: '',
  status: ''
})

// 采购入库单列表数据
const stockInList = ref([])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 仓库列表
const warehouses = ref([])

// 供应商列表
const suppliers = ref([])

// 采购订单列表
const purchaseOrders = ref([])

// 对话框数据
const dialogVisible = ref(false)
const dialogType = ref('') // 'create', 'edit', 'view', 'approve'
const dialogTitle = ref('')
const stockInForm = reactive({
  id: 0,
  stockInCode: '',
  stockInDate: '',
  warehouseId: '',
  supplierId: '',
  purchaseOrderId: '',
  remark: '',
  details: []
})
const stockInFormRef = ref(null)

// 审核表单数据
const approveForm = reactive({
  approvalRemark: ''
})
const approveFormRef = ref(null)

// 格式化状态
const formatStatus = (row) => {
  const statusMap = {
    'pending': '待审核',
    'approved': '已审核',
    'rejected': '已拒绝',
    'canceled': '已作废'
  }
  return statusMap[row.status] || row.status
}

// 加载采购入库单列表数据
const loadStockInList = async () => {
  try {
    const response = await axios.get('/api/PurchaseStockIns', {
      params: {
        page: pagination.currentPage,
        pageSize: pagination.pageSize,
        stockInCode: searchForm.stockInCode,
        stockInDate: searchForm.stockInDate,
        warehouseId: searchForm.warehouseId,
        supplierId: searchForm.supplierId,
        purchaseOrderCode: searchForm.purchaseOrderCode,
        status: searchForm.status
      }
    })
    stockInList.value = response.data.items
    pagination.total = response.data.total
  } catch (error) {
    ElMessage.error('获取采购入库单列表失败: ' + error.message)
    console.error('Failed to load purchase stock in list:', error)
  }
}

// 加载仓库列表
const loadWarehouses = async () => {
  try {
    const response = await axios.get('/api/Warehouses')
    warehouses.value = response.data
  } catch (error) {
    ElMessage.error('获取仓库列表失败: ' + error.message)
  }
}

// 加载供应商列表
const loadSuppliers = async () => {
  try {
    const response = await axios.get('/api/Suppliers')
    suppliers.value = response.data
  } catch (error) {
    ElMessage.error('获取供应商列表失败: ' + error.message)
  }
}

// 加载采购订单列表
const loadPurchaseOrders = async () => {
  try {
    const response = await axios.get('/api/PurchaseOrders')
    purchaseOrders.value = response.data
  } catch (error) {
    ElMessage.error('获取采购订单列表失败: ' + error.message)
  }
}

// 加载采购订单明细
const loadPurchaseOrderDetails = async (orderId) => {
  try {
    const response = await axios.get(`/api/PurchaseOrders/${orderId}/details`)
    return response.data
  } catch (error) {
    ElMessage.error('获取采购订单明细失败: ' + error.message)
    return []
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadStockInList()
}

// 重置
const handleReset = () => {
  searchForm.stockInCode = ''
  searchForm.stockInDate = ''
  searchForm.warehouseId = ''
  searchForm.supplierId = ''
  searchForm.purchaseOrderCode = ''
  searchForm.status = ''
  pagination.currentPage = 1
  loadStockInList()
}

// 分页大小变更
const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadStockInList()
}

// 当前页变更
const handleCurrentChange = (current) => {
  pagination.currentPage = current
  loadStockInList()
}

// 打开创建对话框
const handleCreate = () => {
  dialogType.value = 'create'
  dialogTitle.value = '创建采购入库单'
  stockInForm.id = 0
  stockInForm.stockInCode = ''
  stockInForm.stockInDate = new Date()
  stockInForm.warehouseId = ''
  stockInForm.supplierId = ''
  stockInForm.purchaseOrderId = ''
  stockInForm.remark = ''
  stockInForm.details = []
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  dialogTitle.value = '编辑采购入库单'
  try {
    const response = await axios.get(`/api/PurchaseStockIns/${row.id}`)
    Object.assign(stockInForm, response.data)
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取采购入库单详情失败: ' + error.message)
  }
}

// 打开查看对话框
const handleView = async (row) => {
  dialogType.value = 'view'
  dialogTitle.value = '查看采购入库单'
  try {
    const response = await axios.get(`/api/PurchaseStockIns/${row.id}`)
    Object.assign(stockInForm, response.data)
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取采购入库单详情失败: ' + error.message)
  }
}

// 打开审核对话框
const handleApprove = async (row) => {
  dialogType.value = 'approve'
  dialogTitle.value = '审核采购入库单'
  try {
    const response = await axios.get(`/api/PurchaseStockIns/${row.id}`)
    Object.assign(stockInForm, response.data)
    approveForm.approvalRemark = ''
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取采购入库单详情失败: ' + error.message)
  }
}

// 删除采购入库单
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个采购入库单吗？', '确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await axios.delete(`/api/PurchaseStockIns/${row.id}`)
    ElMessage.success('删除成功')
    loadStockInList()
  } catch (error) {
    if (error.name !== 'Error') {
      ElMessage.error('删除失败: ' + error.message)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await stockInFormRef.value.validate()
    if (dialogType.value === 'create') {
      await axios.post('/api/PurchaseStockIns', stockInForm)
      ElMessage.success('创建成功')
    } else if (dialogType.value === 'edit') {
      await axios.put(`/api/PurchaseStockIns/${stockInForm.id}`, stockInForm)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    loadStockInList()
  } catch (error) {
    ElMessage.error('提交失败: ' + error.message)
  }
}

// 审核通过
const handleApproveSubmit = async () => {
  try {
    await axios.patch(`/api/PurchaseStockIns/${stockInForm.id}/approve`, {
      ApprovalRemark: approveForm.approvalRemark,
      ApprovedBy: '1' // 假设当前用户ID为1，实际应从登录信息获取
    })
    ElMessage.success('审核通过')
    dialogVisible.value = false
    loadStockInList()
  } catch (error) {
    ElMessage.error('审核失败: ' + error.message)
  }
}

// 审核拒绝
const handleRejectSubmit = async () => {
  try {
    await axios.patch(`/api/PurchaseStockIns/${stockInForm.id}/status`, 'rejected')
    ElMessage.success('已拒绝')
    dialogVisible.value = false
    loadStockInList()
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message)
  }
}

// 监听采购订单变化，加载订单明细
watch(() => stockInForm.purchaseOrderId, async (newValue) => {
  if (newValue && dialogType.value !== 'view') {
    const details = await loadPurchaseOrderDetails(newValue)
    stockInForm.details = details.map((item, index) => ({
      lineNum: index + 1,
      materialCode: item.materialCode,
      materialName: item.materialName,
      specification: item.specification,
      unit: item.unit,
      orderQuantity: item.quantity,
      inQuantity: item.quantity, // 默认全部入库
      unitPrice: item.unitPrice,
      amount: item.amount,
      batchNumber: '',
      productionDate: '',
      expiryDate: ''
    }))
  }
})

// 初始化加载数据
onMounted(() => {
  loadStockInList()
  loadWarehouses()
  loadSuppliers()
  loadPurchaseOrders()
})
</script>

<style scoped>
.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.detail-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.approve-form {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}
</style>